//
//  HJSuperstarSoccerController.m
//  Keping
//
//  Created by a on 2017/9/3.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "HJSuperstarSoccerController.h"

#import "HJSuperstarSoccerCell.h"

#import "HJHeaderImgView.h"

#import "HJCellModel.h"
#import "HJShopViewsData.h"
#import "HJSuperstarBookRequest.h"
#import "KShopsDetailRequest.h"
#import "HJSuperstarSoccerView.h"
#import "HJSuperstarSoccerTimeCell.h"
#import <XXNibBridge/XXNibBridge.h>

@interface HJSuperstarSoccerController ()<UITableViewDelegate,UITableViewDataSource,HJSelectDateViewDelegate, UIGestureRecognizerDelegate>
/**
 tableView
 */
@property(nonatomic,weak) UITableView*tableView;
/**
 预约按钮
 */
@property(nonatomic,weak)UIButton*bookBtn;
/**
 数据源
 */
@property(nonatomic,strong)NSMutableArray *dataAry;
/**
 内容源
 */
@property(nonatomic,strong)NSMutableArray*contentAry;
/**
 商家详情
 */
@property(nonatomic,strong)KShopViewData*shopViewsData;
@property (nonatomic, strong) KShopItemView *selectShopItemView;
@property (nonatomic, strong) HJSuperstarSoccerView *superstarSoccerView;


@end

@implementation HJSuperstarSoccerController

-(NSMutableArray *)dataAry
{
    if (!_dataAry) {
        HJCellModel*cell1=[HJCellModel cellModelTitle:@"Court Name" content:@""];
        HJCellModel*cell2=[HJCellModel cellModelTitle:@"Date" content:@""];
        HJCellModel*cell3=[HJCellModel cellModelTitle:@"Time" contents:nil];
        _dataAry=[@[@[cell1],@[cell2],@[cell3]] mutableCopy];
    }
    return _dataAry;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    
    [self getData];
}

-(void)setUI
{
    self.navigationItem.title = self.shopViewData.storeName;
    UITableView*tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.estimatedSectionHeaderHeight=0;
    tableView.estimatedSectionFooterHeight=0;
    self.tableView=tableView;
    [self.view addSubview:tableView];

    HJHeaderImgView*headerView=[HJHeaderImgView headerImgView:KAppointmentTypeForVisit];
    headerView.imgUrl=self.shopViewData.logo;
    tableView.tableHeaderView=headerView;
    
    //添加table尾部
    UIView*footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, K_FactorH(80))];
    tableView.tableFooterView=footerView;
    footerView.backgroundColor=[UIColor clearColor];
    CGFloat margin =K_FactorW(20);
    UIButton*bookBtn=[[UIButton alloc]initWithFrame:CGRectMake(margin, K_FactorH(30), footerView.width-2*margin, footerView.height-K_FactorH(30))];
    self.bookBtn=bookBtn;
    [footerView addSubview:bookBtn];
    bookBtn.layer.cornerRadius=bookBtn.height/2;
    bookBtn.layer.masksToBounds=YES;
    [bookBtn setBackgroundColor:[UIColor colorWithHexString:@"#6853fa"] forState:UIControlStateNormal];
    [bookBtn setBackgroundColor:[UIColor grayColor] forState:UIControlStateSelected];
    [bookBtn setTitle:@"Book" forState:UIControlStateNormal];
    bookBtn.titleLabel.font=[UIFont boldSystemFontOfSize:20];
    [bookBtn addTarget:self action:@selector(clickBook) forControlEvents:UIControlEventTouchUpInside];
}

-(void)clickBook
{
    HJCellModel *model1 = self.dataAry[0][0];
    if (!StringNotEmpty(model1.cardID)) {
        [self showErrorText:@"Please choose Court Name!"];
        return;
    }
    
    HJCellModel *model2 = self.dataAry[1][0];
    if (!StringNotEmpty(model2.content)) {
        [self showErrorText:@"Please choose Date!"];
        return;
    }
    
    HJCellModel *model3 = self.dataAry[2][0];
    if (!ArrayNotEmpty(model3.contents)) {
        [self showErrorText:@"Please choose Time!"];
        return;
    }
    NSArray *times = model3.contents;
    NSMutableString *timestrings = [NSMutableString new];
    for (int i = 0; i < times.count; i++) {
        KShopItemTimeView *itemtime = [times objectAtIndex:i];
        if (i == 0) {
            [timestrings appendString:@"["];
            [timestrings appendString:[NSString stringWithFormat:@"{\"businessHoursStart\":\"%@\",\"businessHoursEnd\":\"%@\",\"stauts\":\"\"}",itemtime.businessHoursStart,itemtime.businessHoursEnd]];
            if (times.count == 1) {
                [timestrings appendString:@"]"];
            }
        } else if (i == times.count - 1) {
            [timestrings appendString:@","];
            [timestrings appendString:[NSString stringWithFormat:@"{\"businessHoursStart\":\"%@\",\"businessHoursEnd\":\"%@\",\"stauts\":\"\"}",itemtime.businessHoursStart,itemtime.businessHoursEnd]];
            [timestrings appendString:@"]"];
        } else {
            [timestrings appendString:@","];
            [timestrings appendString:[NSString stringWithFormat:@"{\"businessHoursStart\":\"%@\",\"businessHoursEnd\":\"%@\",\"stauts\":\"\"}",itemtime.businessHoursStart,itemtime.businessHoursEnd]];
        }
    }
    HJSuperstarBookRequest *request = [[HJSuperstarBookRequest alloc] init];
    request.params = @{
                       @"bookDay":model2.content,//日期
                       @"bookTimes":timestrings.copy,//时间段
                       @"itemId":model1.cardID,//场馆ID
                       @"shopId":self.shopViewData.id//商店ID
                       };
    WEAKSELF
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            [weakSelf showText:@"Success!"];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"HJSuperstarSoccerNotication" object:nil];
            });
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf showError:request.error];
    }];
}
-(void)getData
{
    [super getData];
    [self showLoading];
    
    KShopsDetailRequest* facilitiesRequest = [[KShopsDetailRequest alloc]initWithShopId:self.shopViewData.id];
    WEAKSELF;
    [facilitiesRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        weakSelf.shopViewsData = [KShopViewData modelWithJSON:request.responseData];
        if (weakSelf.shopViewsData.statusCode != 200) {
            [weakSelf showErrorText:weakSelf.shopViewsData.msg errCode:weakSelf.shopViewsData.statusCode];
        } else {
            [weakSelf.tableView reloadData];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // 点击的view的类名
    KLog(@"%@", NSStringFromClass([touch.view class]));
    // 点击了tableViewCell，view的类名为UITableViewCellContentView，则不接收Touch点击事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

- (void)actionForSuperstarSoccerView:(NSNotification *)cation {
    [self.superstarSoccerView removeFromSuperview];
}

- (HJSuperstarSoccerView *)superstarSoccerView {
    if (!_superstarSoccerView) {
        _superstarSoccerView = [HJSuperstarSoccerView xx_instantiateFromNib];
        [_superstarSoccerView setFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionForSuperstarSoccerView:)];
        gesture.delegate = self;
        [_superstarSoccerView addGestureRecognizer:gesture];
        WEAKSELF
        _superstarSoccerView.superstarSoccerHidden = ^(NSArray<KShopItemTimeView *> *itemTimeViews) {
            [weakSelf actionForSuperstarSoccerView:nil];
            if (!itemTimeViews)
                return;
            
            NSMutableArray *arr = [weakSelf.dataAry[2] mutableCopy];
            HJCellModel *model = [arr objectAtIndex:0];
            model.contents = itemTimeViews;
            
            [arr replaceObjectAtIndex:0 withObject:model];
            [weakSelf.dataAry replaceObjectAtIndex:2 withObject:arr];
            [weakSelf.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
        };
    }
    return _superstarSoccerView;
}

#pragma mark  --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataAry.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataAry[section] count];
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HJSuperstarSoccerCell *cell=[HJSuperstarSoccerCell cellWithTableView:tableView];
    cell.index = indexPath.section;
    cell.cellModel = self.dataAry[indexPath.section][indexPath.row];
    cell.isShowArrow = NO;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return K_FactorH(10);
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return K_FactorH(60);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 && indexPath.row == 0) {
        HJSuperstarSoccerCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        cell.isSelect=!cell.isSelect;
        if (cell.isSelect) {
            //插入场馆的场地
            NSMutableArray*ary=[self.dataAry[0] mutableCopy];
            [ary addObjectsFromArray:self.shopViewsData.shopView.shopItemViews];
            [self.dataAry replaceObjectAtIndex:0 withObject:ary];
            //刷新界面
            [self.tableView reloadSection:0 withRowAnimation:UITableViewRowAnimationNone];
        }else
        {
            //删除场馆的场地
            NSMutableArray*ary = [self.dataAry[0] mutableCopy];
            [ary removeObjectsInArray:self.shopViewsData.shopView.shopItemViews];
            [self.dataAry replaceObjectAtIndex:0 withObject:ary];
            //刷新界面
            [self.tableView reloadSection:0 withRowAnimation:UITableViewRowAnimationNone];
            
        }
    }else if (indexPath.section == 1)
    {
        [self creatDatePicker:UIDatePickerModeDate];
    } else if (indexPath.section == 2) {
        if (self.selectShopItemView) {
            HJCellModel *shopItemTmp1 = self.dataAry[1][0];
            if (!StringNotEmpty(shopItemTmp1.content)) {
                [self showErrorText:@"Please choose Date!"];
                return;
            }
            
            AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [app.window addSubview:self.superstarSoccerView];
            self.superstarSoccerView.shopItemTimeViews = self.selectShopItemView.shopItemTimeViews;
        } else {
            [self showErrorText:@"Please choose Court Name!"];
            return;
        }
    } else
    {
        //选择场馆的场地
        KShopItemView *shopItem = self.dataAry[indexPath.section][indexPath.row];
        HJCellModel *shopItemTmp = self.dataAry[0][0];
        shopItemTmp.content = shopItem.name;
        shopItemTmp.cardID = shopItem.id;
        [self.dataAry replaceObjectAtIndex:0 withObject:@[shopItemTmp]];
        self.selectShopItemView = shopItem;
        [self.tableView reloadSection:0 withRowAnimation:UITableViewRowAnimationNone];
        if ([shopItem.stauts isEqualToString:@"N"]) {
            self.bookBtn.selected = YES;
            self.bookBtn.userInteractionEnabled = NO;
        }
    }
}

-(void)creatDatePicker:(UIDatePickerMode)dateModel
{
    HJCellModel *shopItemTmp = self.dataAry[0][0];
    if (!StringNotEmpty(shopItemTmp.content)) {
        [self showErrorText:@"Please choose Court Name!"];
        return;
    }
    if (dateModel == UIDatePickerModeTime) {
        HJCellModel *shopItemTmp1 = self.dataAry[1][0];
        if (!StringNotEmpty(shopItemTmp1.content)) {
            [self showErrorText:@"Please choose Date!"];
            return;
        }
    }
    
    HJSelectDateView*dateView=[[HJSelectDateView alloc]initWithFrame:CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height)];
    dateView.delegate=self;
    dateView.DateModel=dateModel;
    [self.navigationController.view addSubview:dateView];
}

#pragma mark -- HJSelectDateViewDelegate
-(void)selectDateView:(HJSelectDateView*)selectDateView clickSelectDate:(NSString*)dateStr indexPath:(NSIndexPath*)indexPath {
    
    if (selectDateView.DateModel == UIDatePickerModeDate) {
        NSMutableArray *arr = [self.dataAry[1] mutableCopy];
        HJCellModel *model = [arr objectAtIndex:0];
        model.content = dateStr;
        [arr replaceObjectAtIndex:0 withObject:model];
        [self.dataAry replaceObjectAtIndex:1 withObject:arr];
        [self.tableView reloadSection:1 withRowAnimation:UITableViewRowAnimationNone];
    }
//    else {
//        NSMutableArray *arr = [self.dataAry[2] mutableCopy];
//        HJCellModel *model = [arr objectAtIndex:0];
//
//        if (!StringNotEmpty(model.content) || [model.content containsString:@"-"]) {
//            model.content = dateStr;
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self creatDatePicker:UIDatePickerModeTime];
//            });
//        } else {
//            model.content = [model.content stringByAppendingString:[NSString stringWithFormat:@" - %@",dateStr]];
//        }
//
//
//        [arr replaceObjectAtIndex:0 withObject:model];
//        [self.dataAry replaceObjectAtIndex:2 withObject:arr];
//        [self.tableView reloadSection:2 withRowAnimation:UITableViewRowAnimationNone];
//    }
}

@end
